<template>
	<div>
		<div class="toolbar mt-2">
			<a-form ref="searchRef" :model="searchState" :label-col="{ style: { width: '80px' } }" @finish="current = 1; initData()">
				<a-row :gutter="20">
					<a-col :span="6">
						<a-form-item label="供应商">
							<a-input v-model:value="searchState['company_name']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="手机号">
							<a-input v-model:value="searchState['mobile']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="公司法人">
							<a-input v-model:value="searchState['legal_person']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="委托人">
							<a-input v-model:value="searchState['client']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="创建人">
							<a-input v-model:value="searchState['opr_user']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="企业信用代码">
							<a-input v-model:value="searchState['company_code']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="供应类型">
							<a-select v-model:value="searchState['supplier_material_type_id']" placeholder="请选择供应类型" :options="supplylist" allow-clear></a-select>
						</a-form-item>
					</a-col>
					<a-col :span="4">
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>
						</a-space>
					</a-col>
				</a-row>
			</a-form>
		</div>

		<div class="container mt-2">
			<div class="mb-2">
				<a-space>
					<a-button v-permission="'158'" type="primary" @click="addUser">
						<plus-outlined />添加供应商
					</a-button>
					<a-button v-permission="'161'" danger :disabled="!selectedRowKeys.length" @click="deleteUser">
						<delete-outlined />删除供应商
					</a-button>

					<a-upload v-permission="'162'" name="upload" :show-upload-list="false" :action="`${baseURL}/user/importSupplier`" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="() => uploading = true" @change="changeImport">
						<a-button>
							<template v-if="uploading">
								<loading-outlined />导入中...
							</template>
							<template v-else>
								<import-outlined />导入供应商
							</template>
						</a-button>
					</a-upload>

					<a-button v-permission="'162'" type="link" @click="downloadUserTpl">
						<download-outlined />下载供应商模板
					</a-button>

					<a-button v-permission="'163'" type="link" @click="handleExport">
						<export-outlined />导出
					</a-button>
				</a-space>
			</div>
			<a-table row-key="id" :row-selection="{ selectedRowKeys: selectedRowKeys, onSelect: onSelect, onSelectAll: onSelectAll }" :scroll="tableScroll" :data-source="userSource" :pagination="pagination" :loading="loading" :columns="columns" @change="initData">
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'client'">
						<a-space>
							<a-button v-if="record.clients.length" v-permission="'165'" @click="showClient(record)">查看</a-button>
							<span v-else class="red">暂无</span>
						</a-space>
					</template>
					<template v-if="column.dataIndex === 'company_name'">
						<a-space :class="{ red: checkInfo(record) }">{{ record.company_name }}</a-space>
					</template>
					<!--					<template v-if="column.dataIndex === 'appraise'">-->
					<!--						<a-button v-permission="'217'" @click="showAppraise(record.id)">查看</a-button>-->
					<!--					</template>-->
					<template v-if="column.dataIndex === 'appraise'">
						<a-typography-text v-if="!record.score" style="cursor: pointer" @click="showAppraise(record.id)">暂无评分</a-typography-text>
						<a-rate v-else style="cursor: pointer" :value="record.score * 5 / 100" disabled @click="showAppraise(record.id)" />
					</template>
					<template v-if="column.dataIndex === 'status'">
						<a-space>
							<a-switch v-model:checked="record.status" v-permission:show="'214'" checked-children="启用" un-checked-children="禁用" :checked-value="1" :un-checked-value="0" :loading="record.loading" @click="changeStatus(record)" />
						</a-space>
					</template>
					<template v-if="column.key === 'operation'">
						<a-space>
							<a-button v-permission="'159'" type="link" @click="showUser(record)">
								<right-outlined />查看
							</a-button>
							<a-button v-permission="'164'" type="link" @click="showContract(record)">
								<align-center-outlined />中标信息
							</a-button>
							<a-button v-permission="'160'" type="link" @click="editUser(record)">
								<edit-outlined />修改
							</a-button>
							<a-button v-permission="'161'" type="link" style="color:#ff7875" @click="deleteUser(record.id)">
								<delete-outlined />删除
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>
		</div>
		<a-modal v-model:visible="show" width="1000px" title="查看供应商信息" @ok="handleOk">
			<a-form ref="formRef" v-bind="{ labelCol: { style: { width: '100px' } } }">
				<table cellspacing="0" cellpadding="0" style="width: 100%;">
					<tr>
						<td style="font-size:14px;font-weight:bold;text-align:center" colspan="3">
							<div style="margin-bottom: 10px;">基本信息</div>
						</td>
					</tr>
					<tr>
						<td colspan="3">
							<a-form-item label="公司名称" name="company_name">
								<a-input v-model:value="showData.company_name" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="供应商类别" name="supplier_type">
								<a-select v-model:value="showData.supplier_type" disabled mode="multiple" :options="supplierTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="公司性质" name="company_type">
								<a-select v-model:value="showData.company_type" disabled :options="companyTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="专业" name="major">
								<a-select v-model:value="showData.major" disabled mode="multiple" :options="majorOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="是否是委托人" name="is_consignor">
								<a-switch v-model:checked="showData.is_consignor" :checked-value="1" :un-checked-value="0" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">联系信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="法定代表人" name="legal_person">
								<a-input v-model:value="showData.legal_person" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="法人身份证号" name="legal_person_idcard">
								<a-input v-model:value="showData.legal_person_idcard" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="联系方式" name="contacts_tel">
								<a-input v-model:value="showData.contacts_tel" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="委托人">
								<span v-if="!showData.clients?.length" style="color:red">无</span>
								<span v-else style="color:red" @click="showClient(showData)">(查看)</span>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">登录信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="登录账号" name="username">
								<a-input v-model:value="showData.username" disabled />
							</a-form-item>
						</td>
						<td colspan="2">
							<a-form-item label="登录手机号" name="mobile">
								<a-input v-model:value="showData.mobile" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">开票信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="户名" name="company_name">
								<a-input v-model:value="showData.company_name" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="社会信用代码" name="company_code">
								<a-input v-model:value="showData.company_code" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="地址" name="company_address">
								<a-input v-model:value="showData.company_address" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="电话" name="phone">
								<a-input v-model:value="showData.phone" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="开户行" name="account_bank">
								<a-input v-model:value="showData.account_bank" disabled />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="银行账号" name="company_account">
								<a-input v-model:value="showData.company_account" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">证件及有效期</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="证件类型" name="certificate_type" :rules="{ required: true, message: '请选择证件类型' }">
								<a-select v-model:value="showData.certificate_type" mode="multiple" :show-search="true" placeholder="请选择证件类型" :options="certificateTypeOptions" option-filter-prop="label" disabled></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件文件信息" name="certificate_file_path" :rules="{ required: true, message: '请上传证件文件' }">
								<a-upload v-model:file-list="showData.certificate_file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeUpload" disabled @change="changeUpload">
									<a-button>
										<template v-if="uploading">
											<loading-outlined />上传中...
										</template>
										<template v-else>
											<import-outlined />上传附件
										</template>
									</a-button>
								</a-upload>
								<span style="color:#ccc">
									提交证件文件
									<span style="color:red">PNG,JPG,DOC,EXCEL,PDF</span>文件
								</span>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件有效期" name="certificate_validity" :rules="{ required: true, message: '请输入有效期' }">
								<a-checkbox v-model:checked="showData.certificate_perpetuity" disabled @change="changeCertificatePerpetuity">长期</a-checkbox>
								<a-date-picker v-model:value="showData.certificate_validity" value-format="YYYY-MM-DD" disabled />
							</a-form-item>
						</td>
					</tr>
				</table>
			</a-form>
		</a-modal>
		<a-modal v-model:visible="visible" title="创建供应商" width="1000px" @ok="saveUser">
			<a-form ref="formRef" :model="formState" :rules="formRules" v-bind="{ labelCol: { style: { width: '100px' } } }">
				<!--
				<table cellspacing="0" cellpadding="0" style="width: 100%;">
					<tr>
						<td>
							<a-form-item label="供应商名称" name="company_name">
								<a-input v-model:value="formState.company_name" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="法人" name="legal_person">
								<a-input v-model:value="formState.legal_person" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="社会信用代码" name="company_code">
								<a-input v-model:value="formState.company_code" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="供应商类别" name="supplier_type">
								<a-select v-model:value="formState.supplier_type" multiple>
									<a-select-option v-for="(item) in supplierTypeOptions" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
								</a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="公司性质" name="company_type">
								<a-select v-model:value="formState.company_type" multiple>
									<a-select-option v-for="(item) in companyTypeOptions" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
								</a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="专业" name="major">
								<a-select v-model:value="formState.major" multiple>
									<a-select-option v-for="(item) in majorOptions" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
								</a-select>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="手机号" name="mobile">
								<a-input v-model:value="formState.mobile" placeholder="可用于用户登录" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="联系人" name="contacts">
								<a-input v-model:value="formState.contacts" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="委托人" name="client">
								<a-input v-model:value="formState.client" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="2">
							<a-form-item label="登录密码" name="password">
								<a-input-password v-model:value="formState.password" autocomplete="off" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="重复密码" name="confirm_password">
								<a-input-password v-model:value="formState.confirm_password" autocomplete="off" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="开户行" name="account_bank">
								<a-input v-model:value="formState.account_bank" />
							</a-form-item>
						</td>
						<td colspan="2">
							<a-form-item label="账户" name="company_account">
								<a-input v-model:value="formState.company_account" />
							</a-form-item>
						</td>
					</tr>
				</table>-->
				<table cellspacing="0" cellpadding="0" style="width: 100%;">
					<tr>
						<td style="font-size:14px;font-weight:bold;text-align:center" colspan="3">
							<div style="margin-bottom: 10px;">基本信息</div>
						</td>
					</tr>
					<tr>
						<td colspan="3">
							<a-form-item label="公司名称" name="company_name">
								<a-input v-model:value="formState.company_name" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="供应商类别" name="supplier_type">
								<a-select v-model:value="formState.supplier_type" mode="multiple" :options="supplierTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="公司性质" name="company_type">
								<a-select v-model:value="formState.company_type" :options="companyTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="专业" name="major">
								<a-select v-model:value="formState.major" mode="multiple" :options="majorOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="是否是委托人" name="is_consignor">
								<a-switch v-model:checked="formState.is_consignor" :checked-value="1" :un-checked-value="0" disabled />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3">
							<a-form-item label="经营范围" name="supplier_business_scope">
								<a-textarea v-model:value="formState.supplier_business_scope" placeholder="请输入经营范围" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td style="font-size:14px;font-weight:bold;text-align:center" colspan="3">
							<div style="margin-bottom: 10px;">联系信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="法定代表人" name="legal_person">
								<a-input v-model:value="formState.legal_person" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="联系方式" name="contacts_tel">
								<a-input v-model:value="formState.contacts_tel" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="法人证件类型" name="legal_person_idcard_type">
								<a-select v-model:value="formState.legal_person_idcard_type" placeholder="请选择证件类型" :options="idcardTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="法人证件号" name="legal_person_idcard">
								<a-input v-model:value="formState.legal_person_idcard" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件附件" name="legal_person_idcard_file_path" :rules="{required: formState.legal_person_idcard_type === 2, message:'请提交法人证件附件'}">
								<a-upload v-model:file-list="formState.legal_person_idcard_file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeLegalPersonUpload" @change="changeLegalPersonUpload">
									<a-button>
										<template v-if="uploading">
											<loading-outlined />上传中...
										</template>
										<template v-else>
											<import-outlined />上传附件
										</template>
									</a-button>
								</a-upload>
								<span style="color:#ccc">
									提交证件文件
									<span style="color:red">PNG,JPG,DOC,EXCEL,PDF</span>文件
								</span>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="委托人">
								<span v-if="!formState.clients?.length" style="color:red">无</span>
								<span v-else style="color:red" @click="showClient(formState)">(查看)</span>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td style="font-size:14px;font-weight:bold;text-align:center" colspan="3">
							<div style="margin-bottom: 10px;">登录信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="登录账号" name="username">
								<a-input v-model:value="formState.username" />
							</a-form-item>
						</td>
						<td colspan="2">
							<a-form-item label="登录手机号" name="mobile">
								<a-input v-model:value="formState.mobile" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="登录密码" name="password">
								<a-input-password v-model:value="formState.password" autocomplete="off" />
								<span v-if="formState.id" style="color:#ccc">无需修改密码，则无需录入</span>
							</a-form-item>
						</td>
						<td colspan="2">
							<a-form-item label="重复密码" name="confirm_password">
								<a-input-password v-model:value="formState.confirm_password" autocomplete="off" />
								<span v-if="formState.id" style="color:#ccc">无需修改密码，则无需录入</span>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td style="font-size:14px;font-weight:bold;text-align:center" colspan="3">
							<div style="margin-bottom: 10px;">开票信息</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="户名" name="company_name">
								<a-input v-model:value="formState.company_name" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="社会信用代码" name="company_code">
								<a-input v-model:value="formState.company_code" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="地址" name="company_address">
								<a-input v-model:value="formState.company_address" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="电话" name="company_phone">
								<a-input v-model:value="formState.company_phone" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="开户行" name="account_bank">
								<a-input v-model:value="formState.account_bank" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="银行账号" name="company_account">
								<a-input v-model:value="formState.company_account" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="font-size:14px;font-weight:bold;text-align:center">
							<div style="margin-bottom: 10px;">证件及有效期</div>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="证件类型" name="certificate_type" :rules="{ required: true, message: '请选择证件类型' }">
								<a-select v-model:value="formState.certificate_type" mode="multiple" :show-search="true" placeholder="请选择证件类型" :options="certificateTypeOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件文件信息" name="certificate_file_path" :rules="{ required: true, message: '请上传证件文件' }">
								<a-upload v-model:file-list="formState.certificate_file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeUpload" @change="changeUpload">
									<a-button>
										<template v-if="uploading">
											<loading-outlined />上传中...
										</template>
										<template v-else>
											<import-outlined />上传附件
										</template>
									</a-button>
								</a-upload>
								<span style="color:#ccc">
									提交证件文件
									<span style="color:red">PNG,JPG,DOC,EXCEL,PDF</span>文件
								</span>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="证件有效期" name="certificate_validity" :rules="{ required: true, message: '请输入有效期' }">
								<a-checkbox v-model:checked="formState.certificate_perpetuity" @change="changeCertificatePerpetuity">长期</a-checkbox>
								<a-date-picker v-model:value="formState.certificate_validity" value-format="YYYY-MM-DD" :disabled="formState.certificate_perpetuity" />
							</a-form-item>
						</td>
					</tr>
				</table>
			</a-form>
		</a-modal>
		<a-modal v-model:visible="contractVisible" width="1000px" title="中标信息">
			<a-table :columns="contractColumns" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="contractSource"></a-table>
		</a-modal>
		<a-modal v-model:visible="clientVisible" width="800px" title="委托人信息" style="z-index: 9999">
			<a-table :columns="clientColumns" row-key="id" :data-source="clientSource" :pagination="false">
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'file_path'">
						<a target="_blank" :href="record.file_path?.[0]?.url">{{ record.file_path?.[0]?.name }}</a>
					</template>
					<!--					<template v-if="column.key === 'operation'">-->
					<!--						<a-space>-->
					<!--							<a-button v-permission="'167'" type="link" style="color:#ff7875" @click="deleteClient(record.id)">-->
					<!--								<delete-outlined />删除-->
					<!--							</a-button>-->
					<!--						</a-space>-->
					<!--					</template>-->
					<template v-else-if="column.dataIndex === 'departments'">
						<span v-for="(d, index) in record['departments']" :key="index">
							{{ d.name }} ({{ dayjs(d.UserDepartment?.start_validity).format('YYYY/MM/DD') }} ~ {{ dayjs(d.UserDepartment?.end_validity).format('YYYY/MM/DD') }})
							<br />
						</span>
					</template>
				</template>
			</a-table>
		</a-modal>
		<a-modal v-model:visible="addclientVisible" width="800px" title="添加委托人" @ok="saveClient">
			<a-form ref="clientRef" :model="clientState" :rules="clientRules" v-bind="{ labelCol: { style: { width: '100px' } } }">
				<a-row :gutter="16">
					<a-col :span="8">
						<a-form-item label="委托人姓名" name="name" :rules="{ required: true, message: '请输入委托人姓名' }">
							<a-input v-model:value="clientState.name" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="委托人手机号" name="mobile" :rules="{ required: true, message: '请输入委托人手机号' }">
							<a-input v-model:value="clientState.mobile" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="委托书" name="file_path" :rules="{ required: true, message: '请上传委托书附件' }">
							<a-upload v-model:file-list="clientState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeClientUpload" @change="changeClientUpload">
								<a-button>
									<template v-if="uploading">
										<loading-outlined />上传中...
									</template>
									<template v-else>
										<import-outlined />上传附件
									</template>
								</a-button>
							</a-upload>
							<span style="color:#ccc">
								提交证件照
								<span style="color:red">JPG,PNG</span>文件
							</span>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</div>
</template>
<script setup lang="jsx">
import dayjs from 'dayjs';

import { ExportOutlined, AlignCenterOutlined, SearchOutlined, EditOutlined, DeleteOutlined, ImportOutlined, PlusOutlined, DownloadOutlined, LoadingOutlined, RightOutlined } from "@ant-design/icons-vue";

import { reactive, ref, computed, getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance();

import { post } from "../utils";
import { usePagination } from "vue-request";

//import { Upload } from '../components';

import { baseURL } from '../utils/request';
import { useRoute, useRouter } from "vue-router";

const searchRef = ref();
const supplierRef = ref({});
const searchState = reactive({});
const showData = ref({});
const show = ref(false);
const contractVisible = ref(false);
const clientVisible = ref(false);
const addclientVisible = ref(false);
const companyOptions = ref([]);
const projectOptions = ref([]);
const contractSource = ref([]);
const certificateTypeOptions = ref([]);
const clientSource = ref([]);
const uploading = ref(false);
const clientUploading = ref(false);
const router = useRouter();
const handleOk = () => {
	show.value = false;
}
const initProjects = new Promise((resolve, reject) => {
	post("department/projects?type=3").then(({ data }) => {
		projectOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name,
				parent_ids: d.parent_ids,
			};
		});
		resolve();
	});
})
const supplylist = ref([])
// 供应类别
post("/material/supply/types",).then((data) => {
	console.log('data', data)
	supplylist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		}
	})
});
const initCompany = new Promise((resolve, reject) => {
	post("department/projects?type=2", {
		parent_ids: JSON.stringify([78, 24]),
	}).then(({ data }) => {
		companyOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
		resolve();
	});
})
const initCertificateType = new Promise((resolve, reject) => {
	post("dictionary", { root_id: "1039" }).then(data => {
		certificateTypeOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
		resolve();
	});
});
Promise.all([initProjects, initCompany, initCertificateType])
const contractColumns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	{
		title: "合同名称",
		dataIndex: "name",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left"
	},
	{
		title: "城市公司",
		dataIndex: "project_id",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			const project = projectOptions.value.find(d => d.value === text);
			const parseIds = (project.parent_ids || '').split(',').map(item => parseInt(item));
			return companyOptions.value.find(d => parseIds.includes(d.value))?.label;
		}
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return text.name;
		}
	},
	// {
	// 	title: "合同编号",
	// 	dataIndex: "code",
	// 	sorter: false,
	// 	width: 150,
	// 	ellipsis: true
	// },
	{
		title: "合同总价",
		dataIndex: "amount",
		sorter: false,
		width: 150,
		ellipsis: true
	},
	{
		title: "签订时间",
		dataIndex: "create_time",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	}
];
const clientColumns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	{
		title: "委托人",
		dataIndex: "fullname",
		sorter: false,
		width: 120,
		ellipsis: true,
		fixed: "left"
	},
	{
		title: "电话",
		dataIndex: "mobile",
		sorter: false,
		width: 100,
		ellipsis: true
	},
	{
		title: "绑定项目",
		dataIndex: "departments",
		sorter: false,
		width: 270,
	},
	// {
	// 	title: "操作",
	// 	key: "operation",
	// 	sorter: false,
	// 	fixed: "right",
	// 	width: 150,
	// 	align: "center"
	// }
];


const showContract = record => {
	post("contract", { supplier_id: record.id }).then(({ data }) => {
		contractSource.value = data.map(d => {
			return d;
		});
	});

	contractVisible.value = true;

	supplierRef.value.id = record.id;
	//cinitData();
}
const showClient = record => {
	post("user", { parent_id: record.id, page_size: Infinity, is_consignor: 1 }).then(({ data }) => {
		clientSource.value = data.map(d => {
			return d;
		});
	});
	clientVisible.value = true;
}
const showAppraise = supplierId => {
	router.push(`/supplier/appraise/${supplierId}`);
}
const showaddClient = record => {
	clientState.value = {};
	clientState.value.company_id = record.id;
	addclientVisible.value = true;
}
//1生产制造单位2贸易单位3代理经销4服务提供
const supplierTypeOptions = [
	{
		value: 1,
		label: "生产制造单位"
	},
	{
		value: 2,
		label: "贸易单位"
	},
	{
		value: 3,
		label: "代理经销"
	},
	{
		value: 4,
		label: "服务提供"
	}
]
//1有限公司2股份公司3央企4国企5国资委
const companyTypeOptions = [
	{
		value: 1,
		label: "有限公司"
	},
	{
		value: 2,
		label: "股份公司"
	},
	{
		value: 3,
		label: "央企"
	},
	{
		value: 4,
		label: "国企"
	},
	{
		value: 5,
		label: "国资委"
	}
]
//majorOptions 1劳务作业2专业作业3材料供应4机械租赁5服务提供6回收处理
const majorOptions = [
	{
		value: 1,
		label: "劳务作业"
	},
	{
		value: 2,
		label: "专业作业"
	},
	{
		value: 3,
		label: "材料供应"
	},
	{
		value: 4,
		label: "机械租赁"
	},
	{
		value: 5,
		label: "服务提供"
	},
	{
		value: 6,
		label: "回收处理"
	}
]
//没雨溪:11.15更新 调整只显示劳务作业 专业作业
// majorOptions = majorOptions.filter(item => {
// 		return (item.value === 1 || item.value === 2)
// 	})
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 250 }));

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 60,
		align: 'center',
		fixed: "left"
	},
	{
		title: "供应商",
		dataIndex: "company_name",
		sorter: false,
		align: "center",
		width: 200,
		ellipsis: true
	},
	{
		title: "手机号",
		dataIndex: "mobile",
		sorter: false,
		align: "center",
		width: 120
	},
	{
		title: "委托人",
		dataIndex: "client",
		sorter: false,
		align: "center",
		width: 80
	},
	{
		title: "法人",
		dataIndex: "legal_person",
		sorter: false,
		align: "center",
		width: 100
	},
	{
		title: "供应类型",
		dataIndex: "supplier_material_type",
		sorter: false,
		align: "center",
		width: 100,
		customRender: ({ text, record, index, column }) => {
			return text ? JSON.parse(text).map(d => d.name).join(',') : text;
		}
	},
	{
		title: "供应商类型",
		dataIndex: "supplier_type",
		sorter: false,
		width: 200,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			//return supplierTypeOptions.find(d => d.value === text)?.label
			return text?.split(",").map(d => {
				d = supplierTypeOptions.find(d1 => d1.value === parseInt(d))?.label
				return d;
			}).join(",")
		}
	},
	{
		title: "创建人",
		dataIndex: "opr_user",
		sorter: false,
		width: 100,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text?.fullname || text?.username || '注册'
		}
	},
	{
		title: "最后更新时间",
		dataIndex: "update_time",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "经营范围",
		dataIndex: "supplier_business_scope",
		width: 100,
		align: "center",
		ellipsis: true
	},
	{
		title: "供应商评价",
		dataIndex: "appraise",
		width: 200,
		align: "center",
		fixed: "right",
	},
	{
		title: "状态",
		dataIndex: "status",
		width: 100,
		align: "center",
		fixed: "right",
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 260,
		align: "center"
	}
];

const idcardTypeOptions = [
	{
		value: 1,
		label: "身份证"
	},
	{
		value: 2,
		label: "其他"
	},
]

const selectedRowKeys = ref([]);

/*
const changeSelectedRowKeys = keys => {
	selectedRowKeys.value = keys;
};
*/
const onSelect = (record, selected, selectedRows, nativeEvent) => {
	if (!selected) {
		const index = selectedRowKeys.value.findIndex((d) => d === record.id);
		selectedRowKeys.value.splice(index, 1);
	} else {
		selectedRowKeys.value.push(record.id);
	}
}

const onSelectAll = (selected, selectedRows, changeRows) => {
	if (selected) {
		changeRows.forEach((v) => {
			selectedRowKeys.value.push(v.id);
		})
	} else {
		changeRows.forEach((v) => {
			const index = selectedRowKeys.value.findIndex((d) => d === v.id);
			selectedRowKeys.value.splice(index, 1);
		})
	}
}

const { data, loading, run, runAsync, current, pageSize, total } = usePagination(params => post("supplier", { ...params, ...searchState, show_appraise: true }), {
	defaultParams: [
		{
			page_size: 15
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const userSource = computed(() => data.value?.data || []);
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign({
		current: current.value,
		pageSize: pageSize.value
	}, pag || {});
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
const route = useRoute();
const query = route.query;
if (query) {
	if (query.company_name) searchState.company_name = query.company_name;
	if (query.mobile) searchState.mobile = query.mobile;
	if (query.legal_person) searchState.legal_person = query.legal_person;
	if (query.client) searchState.client = query.client;
	if (query.opr_user) searchState.opr_user = query.opr_user;
	if (query.company_code) searchState.company_code = query.company_code;
	if (query.supplier_material_type_id) searchState.supplier_material_type_id = parseInt(query.supplier_material_type_id);
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const deleteUser = (id) => {
	if (typeof id === "object") id = selectedRowKeys.value.join(",");
	if (!id) {
		proxy.$message.error("请选择需要删除的供应商");
		return;
	}

	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的供应商吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("user/delete", { id }).then(() => {
				proxy.$message.success("供应商删除成功");

				//最后一条记录删除后需要返回上一页
				initData({ current: userSource.value.length === 1 ? Math.max(current.value - 1, 1) : current.value });
			});
		}
	});
}
const deleteClient = (id) => {
	if (!id) {
		proxy.$message.error("请选择需要删除的委托人");
		return;
	}

	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的委托人吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("client/delete", { id }).then(() => {
				proxy.$message.success("操作成功");

				clientVisible.value = false;
			});
		}
	});
}
const visible = ref(false);
const formState = ref({
	certificate_perpetuity: false,
	is_consignor: 1,
});
const formRef = ref();
const clientRef = ref();
const clientState = ref({});

const formRules = computed(() => {
	//const { password } = formState.value;

	return {
		legal_person: [{ required: true, message: "请输入法定代表人", trigger: "blur" }],
		legal_person_idcard: [
			{ required: true, message: "请输入法人身份证号", trigger: "blur" },
		],
		company_code: [{ required: true, message: "请输入社会信用代码", trigger: "blur" }],
		company_account: [{ required: true, message: "请输入开户行", trigger: "blur" }],
		account_bank: [{ required: true, message: "请输入账户", trigger: "blur" }],
		company_name: [{ required: true, message: "请输入供应商", trigger: "blur" }],
		supplier_type: [{ required: true, message: "请选择供应商类别", trigger: "blur" }],
		company_type: [{ required: true, message: "请选择公司性质", trigger: "blur" }],
		major: [{ required: true, message: "请选择专业", trigger: "blur" }],
		username: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
		mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
		contacts: [{ required: true, message: "请输入联系人", trigger: "blur" }],
		client: [{ required: true, message: "请输入委托人", trigger: "blur" }],
		supplier_business_scope: [{ required: true, message: "请输入经营范围", trigger: "blur" }],
		//password: [{ required: true, message: "请输入密码", trigger: "blur" }],
		/**confirm_password: [{
			required: true,
			trigger: "blur",
			validator: (rule, value) => {
				if (!value !== !password) return Promise.reject("确认密码不一致");

				return Promise.resolve();
			}
		}]**/
	}
});
const clientRules = computed(() => {
	return {
		name: [{ required: true, message: "请输入委托人姓名", trigger: "blur" }],
		mobile: [{ required: true, message: "请输入委托人手机号", trigger: "blur" }],
	}
});
const addUser = () => {
	formRef.value?.clearValidate();
	visible.value = true;
	formState.value = {
		department_ids: [],
		is_consignor: 1,
	};
}

const showUser = (record) => {

	show.value = true;
	const data = { ...record };
	data.major_name = "";
	data.supplier_type_name = "";

	data.company_type_name = '';
	majorOptions.forEach((d) => {
		if (d.value === data.major) {
			data.major_name = d.label;
		}
	})
	// majorOptions.forEach((d) => {
	// 	if (d.value === data.major) {
	// 		data.major_name = d.label;
	// 	}	
	// })
	supplierTypeOptions.forEach((d) => {
		if (d.value === data.supplier_type) {
			data.supplier_type_name = d.label;
		}
	})
	companyTypeOptions.forEach((d) => {
		if (d.value === data.company_type) {
			data.company_type_name = d.label;
		}
	})
	data.supplier_type = data.supplier_type?.split(",").map(d => {
		d = parseInt(d);
		return d;
	});
	data.company_type = data.company_type?.split(",").map(d => {
		d = parseInt(d);
		return d;
	})[0];
	data.major = data.major?.split(",").map(d => {
		d = parseInt(d);
		return d;
	});
	data.certificate_type = data.certificate_type ? String(data.certificate_type).split(',').map(item => parseInt(item)) : [];
	data.certificate_perpetuity = data.certificate_validity === '9999-12-31';
	if (data.legal_person_idcard_file_path) {
		data.legal_person_idcard_file_path = [{
			url: data.legal_person_idcard_file_path,
			name: '附件',
		}]
	}
	showData.value = data;
}

const editUser = (record) => {
	formRef.value?.clearValidate();
	visible.value = true;
	const data = { ...record };
	data.birthday = data.birthday ? dayjs(data.birthday) : '';
	data.department_ids = record.departments.map((d) => `${d.company_id}-${d.id}`);
	data.supplier_type = data.supplier_type?.split(",").map(d => {
		d = parseInt(d);
		return d;
	});
	data.company_type = data.company_type?.split(",").map(d => {
		d = parseInt(d);
		return d;
	})[0];
	data.major = data.major?.split(",").map(d => {
		d = parseInt(d);
		return d;
	});
	formState.value = data;
	formState.value.certificate_type = data.certificate_type ? String(data.certificate_type).split(',').map(item => parseInt(item)) : [];
	formState.value.certificate_perpetuity = data.certificate_validity === '9999-12-31';
	if (formState.value.legal_person_idcard_file_path) {
		formState.value.legal_person_idcard_file_path = [{
			url: formState.value.legal_person_idcard_file_path,
			name: '附件',
		}]
	}
}

const saveUser = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };
			params.certificate_file_path = JSON.stringify(params.certificate_file_path);

			if (params.birthday) params.birthday = params.birthday.format('YYYY-MM-DD');
			params.department_ids = params.department_ids?.join(',');
			params.supplier_type = params.supplier_type?.join(",");
			params.major = params.major?.join(",");
			params.is_supplier = 1;
			params.certificate_type = params.certificate_type.join(',');
			if (params.legal_person_idcard_file_path && params.legal_person_idcard_file_path.length) {
				params.legal_person_idcard_file_path = params.legal_person_idcard_file_path[0].url;
			}
			if (params.legal_person_idcard_type === 1) {
				if (!params.legal_person_idcard.match(/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/)) {
					proxy.$message.error("请输入正确的身份证号码");
					return;
				}
			}
			if (params.is_consignor) {
				params.fullname = params.legal_person;
			}
			/*
	  if (!params.username) {
		params.username = "supplier" + Math.random();
	  }
	  */

			post('user/save', params).then(() => {
				proxy.$message.success('提交成功', 1);
				visible.value = false;
				initData();
			}).catch((err) => {
				proxy.$message.error(err);
			});
		})
		.catch(err => {

		});
}
//上传前校验
const beforeUpload = file => {
	uploading.value = true;
	if (!['image/png', 'image/jpeg', 'application/pdf', 'application/vnd.ms-excel', 'application/msword'].includes(file.type)) {
		proxy.$message.error("只能上传PNG,JPG,DOC,EXCEL,PDF文件");
		uploading.value = false;
		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		uploading.value = false;
		return false;
	}
};
//上传前校验
const beforeClientUpload = file => {
	clientUploading.value = true;
	if (!['image/png', 'image/jpeg', 'application/pdf'].includes(file.type)) {
		proxy.$message.error("只能上传照片或PDF文件");
		clientUploading.value = false;
		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		clientUploading.value = false;
		return false;
	}
};

const beforeLegalPersonUpload = file => {
	uploading.value = true;
	if (!['image/png', 'image/jpeg', 'application/pdf', 'application/vnd.ms-excel', 'application/msword'].includes(file.type)) {
		proxy.$message.error("只能上传PNG,JPG,DOC,EXCEL,PDF文件");
		uploading.value = false;
		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		uploading.value = false;
		return false;
	}
};
const changeLegalPersonUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.legal_person_idcard_file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		uploading.value = false;
		proxy.$message.success("上传成功");
	}
};
// 上传并提交文件
const changeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.certificate_file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		uploading.value = false;
		formState.value.certificate_file_path = formState.value.certificate_file_path.filter((item) => item.url);
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		formState.value.certificate_file_path = formState.value.certificate_file_path.filter((item) => item.url);
	}
};
// 上传并提交文件
const changeClientUpload = ({ file }) => {
	if (file.status === "done") {
		clientState.value.file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];

		clientUploading.value = false;
		proxy.$message.success("上传成功");
	}
};
const saveClient = () => {
	clientRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...clientState.value };
			params.file_path = JSON.stringify(params.file_path);
			post('client/save', params).then(() => {
				proxy.$message.success('提交成功', 1);
				addclientVisible.value = false;
			}).catch((err) => {
				proxy.$message.error(err);
			});
		})
		.catch(err => {

		});
}

const departmentSource = ref();
post("company/tree").then(data => {
	departmentSource.value = data.map((d) => {
		//判断是否为公司
		if (d.value.slice(-2) === '-0') {
			//d.disabled = true;
			//d.disableCheckbox = true;

			//分公司不可选
			d.selectable = false;
		}
		return d;
	});
});

const downloadUserTpl = () => {
	window.open(`${baseURL.replace('/api', '')}/uploadfile/tpl-supplier.xlsx`)
}

const handleExport = () => {
	post("supplier", {
		page_size: 10000,
		submit: 'export',
		show_appraise: true,
		ids: selectedRowKeys.value.join(','),
		...searchState
	}).then(({ url }) => {
		if (url) window.location.href = url;
	})
}

const changeImport = (e) => {
	if (e.file.status === 'done') {
		uploading.value = false;
		proxy.$message.success('导入成功');
		initData();
	}
}
const changeCertificatePerpetuity = () => {
	if (formState.value.certificate_perpetuity) {
		formState.value.certificate_validity = '9999-12-31'
	} else {
		formState.value.certificate_validity = dayjs(new Date()).format('YYYY-MM-DD');
		// formState.value.certificate_validity = null;
	}
}
const checkInfo = (item) => {
	if (!item.company_type) return true;
	if (!item.legal_person_idcard) return true;
	if (!item.legal_person) return true;
	if (!item.company_code) return true;
	if (!item.account_bank) return true;
	if (!item.company_account) return true;
	if (!item.certificate_type) return true;
	if (!item.certificate_file_path) return true;
	if (!item.certificate_validity) return true;
	return false;
}

const changeStatus = (record) => {
	record.loading = true;
	post("user/save", { id: record.id, status: record.status })
		.then(() => {
			proxy.$message.success('操作成功', 1).then(async () => {
				record.loading = false;
				initData()
			});
		})
		.catch(err => {
			proxy.$message.error(err);
			record.loading = false;
			initData()
		});
}
</script>

<style scoped scss>
.toolbar {
	padding: 12px;
	background: #fff;
}

.container {
	background: #fff;
	padding: 12px;
}

:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-radio-disabled + span) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
}

.red {
	color: red;
}
</style>
